package com.fyzk.activity.user;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.user.accountdetail.WithDrawRecordActivity;
import com.fyzk.base.BaseActivity;
import com.fyzk.bean.AccountMoneyResponse;
import com.fyzk.bean.BankListResponse;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.dialog.SureDialog;
import com.fyzk.net.Commands;
import com.fyzk.net.PublicMethod;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LogUtils;
import com.fyzk.utils.TextStyleUtil;
import com.fyzk.view.TopTitleView;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

import http.Common.CommandUtil;
import http.StringResultBean;

@ContentView(R.layout.user_tixian)
public class WithdrawCashActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {
    private Context context = this;
    @ViewInject(R.id.withdrawUI_topTitleView)
    private TopTitleView topView;

    @ViewInject(R.id.withdrawUI_tvUserName)
    private TextView userName_tv;

    @ViewInject(R.id.withdrawUI_tvAllow)
    private TextView keTi_tv;
    private double keTiMoney = 0;

    @ViewInject(R.id.withdrawUI_etMoney)
    private EditText money_et;

    @ViewInject(R.id.withdrawUI_tvManage)
    private TextView manage_tv;

    @ViewInject(R.id.withdrawUI_tvOk)
    private TextView tiXian_tv;

//    @ViewInject(R.id.withdrawUI_tvInfor)
//    private TextView tvInfor;

    @ViewInject(R.id.withdrawUI_rgWithdrawType)
    private RadioGroup rg;

    @ViewInject(R.id.withdrawUI_tvBindBank)
    private TextView addBank_tv;
//    @ViewInject(R.id.withdrawUI_tvBindAlipay)
//    private TextView addAlipay_tv;

    @ViewInject(R.id.withdrawUI_rgIntoTime)
    private RadioGroup mRgIntoTime;
    @ViewInject(R.id.withdrawUI_rbtTomorrow)
    private RadioButton mRbtTomorrow;
    @ViewInject(R.id.withdrawUI_rbtToday)
    private RadioButton mRbtToday;
    // 到账时间类型 4：T+1到账 5：即时到账
    private int drawType = 4;

    private RadioButton bankInfo_rb;
//    private RadioButton alipayInfo_rb;
    private TextView tvBank;
//    private TextView tvAlipay;

    private String userName;
    private String realName;
    private String drawContent;

    private int minMoney = 20;
    private Drawable delete_drawable;
    private Drawable choose_drawable;
    private Drawable choose_drawable2;

    private boolean isManage = false;

    private BankListResponse bankInfo;
//    private BankListResponse alipayInfo;
    private BankListResponse chooseInfo;
    private int deleteType;
//    private View mAli;
    private View mLine;
    private View mBank;
    private String drawChannel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        userName = MySharedPreferences.getInstance().getUserName();
        drawContent = MySharedPreferences.getInstance().getDrawContent();
        realName = getIntent().getStringExtra(IntentParamUtils.REALNAME);

        delete_drawable = getResources().getDrawable(R.drawable.tixian_delete);
        delete_drawable.setBounds(0, 0, delete_drawable.getIntrinsicWidth(), delete_drawable.getIntrinsicHeight());
        choose_drawable = getResources().getDrawable(R.drawable.tixian_rb_bg);
        choose_drawable.setBounds(0, 0, choose_drawable.getIntrinsicWidth(), choose_drawable.getIntrinsicHeight());
        choose_drawable2 = getResources().getDrawable(R.drawable.tixian_rb_bg);
        choose_drawable2.setBounds(0, 0, choose_drawable2.getIntrinsicWidth(), choose_drawable2.getIntrinsicHeight());

        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();
        //请求获取彩金
        requestLeftMoney();
        //请求获取银行卡信息
        requestBankList();
    }

    //控件初始化
    private void initView() {
        topView.setOnTitleClickListener(this);
        userName_tv.setText(userName);
      //  tvInfor.setText(drawContent);

//        mAli = LayoutInflater.from(this).inflate(R.layout.withcarsh_rl_ali, rg, false);
//        alipayInfo_rb = mAli.findViewById(R.id.ll_alipayinfo);
//        tvAlipay = mAli.findViewById(R.id.tv_alipayinfo);

        mLine = LayoutInflater.from(this).inflate(R.layout.withcarsh_line, rg, false);

        mBank = LayoutInflater.from(this).inflate(R.layout.withcarsh_rl_bank, rg, false);
        bankInfo_rb = mBank.findViewById(R.id.ll_bankinfo);
        tvBank = mBank.findViewById(R.id.tv_bankinfo);

        manage_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isManage = !isManage;
                if (isManage) {
//                     && alipayInfo == null
                    if (bankInfo == null) {
                        AppToast.getToast().show("请先绑定提现账号");
                        return;
                    }
                    bankInfo_rb.setEnabled(true);
//                    alipayInfo_rb.setEnabled(true);
                    manage_tv.setText(R.string.tixian_manage2);
                    bankInfo_rb.setCompoundDrawables(delete_drawable, null, null, null);
//                    alipayInfo_rb.setCompoundDrawables(delete_drawable, null, null, null);
                } else {
                    if ("3".equals(drawWay)) {
                        bankInfo_rb.setEnabled(false);
//                        alipayInfo_rb.setEnabled(false);
                    } else if ("2".equals(drawWay)) {
//                        alipayInfo_rb.setEnabled(false);
                    } else if ("1".equals(drawWay)) {
                        bankInfo_rb.setEnabled(false);
                    }
                    manage_tv.setText(R.string.tixian_manage);
                    bankInfo_rb.setCompoundDrawables(choose_drawable, null, null, null);
//                    alipayInfo_rb.setCompoundDrawables(choose_drawable2, null, null, null);
                }
            }
        });

        mRbtTomorrow.setText(initTomorrowSpanStr());
        mRbtToday.setText(initTodaySpanStr());

        //事件
        bankInfo_rb.setOnClickListener(this);
//        alipayInfo_rb.setOnClickListener(this);
        addBank_tv.setOnClickListener(this);
//        addAlipay_tv.setOnClickListener(this);
        tiXian_tv.setOnClickListener(this);
        mRgIntoTime.setOnCheckedChangeListener(this);
    }

    private SpannableString initTomorrowSpanStr(){
        String tomorrowStr = "T+1到账（第二天到账0手续费）";
        int startIndex1 = 5;
        int endIndex1 = tomorrowStr.length();
        SpannableString tomorrowSpanStr = new SpannableString(tomorrowStr);
        tomorrowSpanStr.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.race_color_tab_text_color)),
                startIndex1, endIndex1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return tomorrowSpanStr;
    }

    private SpannableString initTodaySpanStr(){
        String todayStr = "实时到账（需3元手续费，仅支持银行卡）";
        int startIndex2 = 4;
        int endIndex2 = todayStr.length();
        SpannableString todaySpanStr = new SpannableString(todayStr);
        todaySpanStr.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.race_color_tab_text_color)),
                startIndex2, endIndex2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return todaySpanStr;
    }

    private SpannableString initTomorrowAlphaSpanStr(){
        String tomorrowStr = "T+1到账（第二天到账0手续费）";
        int startIndex1 = 5;
        int endIndex1 = tomorrowStr.length();
        SpannableString tomorrowAlphaSpanStr = new SpannableString(tomorrowStr);
        tomorrowAlphaSpanStr.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_fe4a4b_alpha90)),
                startIndex1, endIndex1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return tomorrowAlphaSpanStr;
    }

    private SpannableString initTodayAlphaSpanStr(){
        String todayStr = "实时到账（需3元手续费，仅支持银行卡）";
        int startIndex2 = 4;
        int endIndex2 = todayStr.length();
        SpannableString todayAlphaSpanStr = new SpannableString(todayStr);
        todayAlphaSpanStr.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_fe4a4b_alpha90)),
                startIndex2, endIndex2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return todayAlphaSpanStr;
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.withdrawUI_rbtTomorrow:
                drawType = 4;
                break;
            case R.id.withdrawUI_rbtToday:
                drawType = 5;
                break;
        }
    }

    //查询账户彩金
    private void requestLeftMoney() {
        httpPostJson(CommandUtil.ACCOUNT_MONEY, Commands.ACCOUNT_MONEY, null, true);
    }

    //查询用户认证的银行卡列表
    private void requestBankList() {
        httpPostJson(CommandUtil.BANK_CARD_MANAGEMENT, Commands.FINDUSERDRAWBIND, null, false);
    }

    //请求解除银行卡绑定
    private void requestUnBind(String bankId) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("id", bankId);
            httpPostJson(CommandUtil.BANK_DELETE, Commands.USERUNBIND, request_json, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提现
     */
    private void requestTixian() {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("drawType", drawType);
            request_json.put("cardid", chooseInfo.getId());
            request_json.put("drawAmount", Long.parseLong(money_et.getText().toString() + "00"));
            request_json.put("drawbalance", accountMoneyResponse.getDrawbalance());

            LogUtils.e("====request_json====" + request_json.toString());

            httpPostJson(CommandUtil.WITHDRAW, Commands.DRAWAMOUNT, request_json, true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private AccountMoneyResponse accountMoneyResponse;

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.ACCOUNT_MONEY:
                accountMoneyResponse = JSON.parseObject(resultBean.getData(),
                        AccountMoneyResponse.class);
                keTiMoney = accountMoneyResponse.getDrawbalance();
                keTi_tv.setText(Html.fromHtml("可提现彩金：<font color='#5C96F9'>" + PublicMethod.formatBalance(keTiMoney) + "米</font>"));

                drawChannel = accountMoneyResponse.getDrawChannel();
                if (!TextUtils.isEmpty(drawChannel)) {
                    refreshRadioGroup(drawChannel);
                }

                break;
            case CommandUtil.BANK_CARD_MANAGEMENT:
                List<BankListResponse> bankListResponse = JSON.parseArray(resultBean.getData(), BankListResponse
                        .class);

                for (int i = 0; i < bankListResponse.size(); i++) {
                    if (bankListResponse.get(i).getDrawType() == 2) {
//                        alipayInfo = bankListResponse.get(i);
                    } else {
                        bankInfo = bankListResponse.get(i);
                    }
                }
                if (isManage) {
                    isManage = !isManage;
                    manage_tv.setText(R.string.tixian_manage);
                    bankInfo_rb.setCompoundDrawables(choose_drawable, null, null, null);
//                    alipayInfo_rb.setCompoundDrawables(choose_drawable2, null, null, null);
                }

                kongJianFuZhi();
                break;
            case CommandUtil.BANK_DELETE:
                AppToast.getToast().show("已删除");
                if (deleteType == 0) {
                    bankInfo = null;
                } else {
//                    alipayInfo = null;
                }
                kongJianFuZhi();
                break;
            case CommandUtil.WITHDRAW:
                AppToast.getToast().show("提现请求已发送");
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * drawChannel 0|0
     * <p>
     * 前
     * 0（允许银行卡和支付宝）
     * 1（允许支付宝）
     * 2（允许银行卡）
     * 3（禁止所有通道）
     * <p>
     * 后
     * 0 支持T+1,支持时时到账
     * 1 支持T+1,不支持时时到账
     * 2 不支持T+1,支持时时到账
     * <p>
     * 例
     * 0|0  允许银行卡和支付宝  支持T+1,支持时时到账
     * 0|1  允许银行卡和支付宝  支持T+1,不支持时时到账
     * 0|2  允许银行卡和支付宝  不支持T+1,支持时时到账
     *
     * @param drawChannel
     */
    String drawWay = "0";
    String drawTime = "0";
    private void refreshRadioGroup(String drawChannel) {
        String[] drawChannelArray = drawChannel.split("\\|");
        if (drawChannelArray.length == 2) {
            drawWay = drawChannelArray[0];
            drawTime = drawChannelArray[1];
            if ("3".equals(drawWay)) {
                //（禁止所有通道）
                mRbtTomorrow.setBackgroundResource(R.drawable.shanp_draw_shade);
                mRbtToday.setBackgroundResource(R.drawable.shanp_draw_shade);
                mRbtTomorrow.setChecked(false);
                mRbtTomorrow.setEnabled(false);
                mRbtToday.setChecked(false);
                mRbtToday.setEnabled(false);
                mRbtTomorrow.setTextColor(
                        ContextCompat.getColor(context, R.color.color_111111_alpha));
                mRbtToday.setTextColor(
                        ContextCompat.getColor(context, R.color.color_111111_alpha));
                mRbtTomorrow.setText(initTomorrowAlphaSpanStr());
                mRbtToday.setText(initTodayAlphaSpanStr());

//                mAli.setBackgroundResource(R.drawable.shanp_draw_shade);
                mBank.setBackgroundResource(R.drawable.shanp_draw_shade);
//                alipayInfo_rb.setChecked(false);
//                alipayInfo_rb.setEnabled(false);
                bankInfo_rb.setChecked(false);
                bankInfo_rb.setEnabled(false);
//                alipayInfo_rb.setTextColor(
//                        ContextCompat.getColor(context, R.color.color_111111_alpha));
                bankInfo_rb.setTextColor(
                        ContextCompat.getColor(context, R.color.color_111111_alpha));

                tiXian_tv.setBackgroundResource(R.drawable.shanp_draw_btn);
                tiXian_tv.setText("暂不支持提现");
                tiXian_tv.setEnabled(false);
            } else if ("2".equals(drawWay)) {
                //（允许银行卡）
//                mAli.setBackgroundResource(R.drawable.shanp_draw_shade);
//                alipayInfo_rb.setChecked(false);
//                alipayInfo_rb.setEnabled(false);
//                alipayInfo_rb.setTextColor(
//                        ContextCompat.getColor(context, R.color.color_111111_alpha));
                bankInfo_rb.setChecked(true);
                chooseInfo = bankInfo;
            } else if ("1".equals(drawWay)) {
                //（允许支付宝）
                mBank.setBackgroundResource(R.drawable.shanp_draw_shade);
                bankInfo_rb.setChecked(false);
                bankInfo_rb.setEnabled(false);
                bankInfo_rb.setTextColor(
                        ContextCompat.getColor(context, R.color.color_111111_alpha));
//                alipayInfo_rb.setChecked(true);
//                chooseInfo = alipayInfo;
            }

            if ("1".equals(drawTime)) {
                // 支持T+1,不支持时时到账
                mRbtToday.setBackgroundResource(R.drawable.shanp_draw_shade);
                mRbtToday.setChecked(false);
                mRbtToday.setEnabled(false);
                mRbtToday.setTextColor(
                        ContextCompat.getColor(context, R.color.color_111111_alpha));
                mRbtToday.setText(initTodayAlphaSpanStr());
                mRbtTomorrow.setChecked(true);
                drawType = 4;
            } else if ("2".equals(drawTime)) {
                // 不支持T+1,支持时时到账
                mRbtTomorrow.setBackgroundResource(R.drawable.shanp_draw_shade);
                mRbtTomorrow.setChecked(false);
                mRbtTomorrow.setEnabled(false);
                mRbtTomorrow.setTextColor(
                        ContextCompat.getColor(context, R.color.color_111111_alpha));
                mRbtTomorrow.setText(initTomorrowAlphaSpanStr());
                mRbtToday.setChecked(true);
                drawType = 5;
            }
        }
    }

    @Override
    protected void onFailure(int requestCode, String errorCode, String message) {
        cancelProgressDialog();
        switch (requestCode) {
            case CommandUtil.BANK_CARD_MANAGEMENT:
                if (errorCode.equals("900003")) {
                    bankInfo = null;
//                    alipayInfo = null;
                    kongJianFuZhi();
                }
                break;
            case CommandUtil.WITHDRAW:
                showToast(message);
                break;
        }
    }

    /**
     * 控件赋值
     */
    private void kongJianFuZhi() {
        //  && alipayInfo == null
        if (bankInfo != null) {
            rg.removeAllViews();
            rg.addView(mBank);
//            rg.addView(mLine);
//            rg.addView(mAli);
        } else {
            rg.removeAllViews();
//            rg.addView(mAli);
//            rg.addView(mLine);
            rg.addView(mBank);
        }
        if (bankInfo == null) {
            addBank_tv.setVisibility(View.VISIBLE);
            bankInfo_rb.setVisibility(View.GONE);
            tvBank.setVisibility(View.GONE);
        } else {
            addBank_tv.setVisibility(View.GONE);
            bankInfo_rb.setVisibility(View.VISIBLE);
            tvBank.setVisibility(View.VISIBLE);
            bankInfo_rb.setChecked(true);
            bankInfo_rb.setText("");
            tvBank.setText("");
            SpannableString spanString = TextStyleUtil.fontSizeSpan(new SpannableString(bankInfo.getBankName()), 14);
            bankInfo_rb.append(spanString);
            spanString = TextStyleUtil.fontSizeSpan(new SpannableString("  " + PublicMethod.tv_yinCang(bankInfo.getBankCard(), 3, 3)), 12);
            tvBank.append(spanString);
            chooseInfo = bankInfo;
        }

//        if (alipayInfo == null) {
//            addAlipay_tv.setVisibility(View.VISIBLE);
//            alipayInfo_rb.setVisibility(View.GONE);
//            tvAlipay.setVisibility(View.GONE);
//        } else {
//            addAlipay_tv.setVisibility(View.GONE);
//            alipayInfo_rb.setVisibility(View.VISIBLE);
//            tvAlipay.setVisibility(View.VISIBLE);
//            if (bankInfo == null) {
//                alipayInfo_rb.setChecked(true);
//                chooseInfo = alipayInfo;
//            } else {
//                alipayInfo_rb.setChecked(false);
//            }
//            alipayInfo_rb.setText("");
//            tvAlipay.setText("");
//            SpannableString spanString = TextStyleUtil.fontSizeSpan(new SpannableString(alipayInfo.getBankName()), 14);
//            alipayInfo_rb.append(spanString);
//            spanString = TextStyleUtil.fontSizeSpan(new SpannableString("  " + PublicMethod.tv_yinCang(alipayInfo.getBankCard(), 3, 3)), 12);
//            tvAlipay.append(spanString);
//        }
        money_et.requestFocus();
    }

    /**
     * 非空验证
     */
    private boolean isNull(EditText editText) {
        if (editText.getText() == null || editText.getText().toString().equals("")) {
            editText.requestFocus();
            return true;
        }
        return false;
    }

    /**
     * 输入框验证
     *
     * @return
     */
    private boolean et_yanZheng() {

        if (isNull(money_et)) {
            AppToast.getToast().show("提款彩金不能为空");
            return false;
        }

        long jinE = 0;
        try {
            jinE = Long.parseLong(money_et.getText().toString());
        } catch (Exception e) {
        }
        if (jinE < minMoney) {
            AppToast.getToast().show("提款彩金不能小于 " + minMoney + " 米");
            return false;
        }

        if (Double.parseDouble(money_et.getText().toString()) * 100 > keTiMoney) {
            AppToast.getToast().show("可提款彩金不足");
            return false;
        }

        //  && alipayInfo == null
        if (bankInfo == null) {
            AppToast.getToast().show("未设置提现方式，请先设置");
            return false;
        }

        if (chooseInfo == null) {
            AppToast.getToast().show("请选择提现账号");
            return false;
        }

        if (drawType == 5 && chooseInfo != bankInfo) {
            AppToast.getToast().show("实时到账仅支持银行卡");
            return false;
        }

        return true;
    }


    /**
     * 单击事件
     *
     * @author Administrator
     */
    @Override
    public void onClick(View arg0) {
        Intent intent;
        switch (arg0.getId()) {
            case R.id.withdrawUI_tvBindBank:
                intent = new Intent(context, BindBankActivity.class);
                intent.putExtra(IntentParamUtils.USERNAME, userName);
                intent.putExtra(IntentParamUtils.REALNAME, realName);
                startActivity(intent);
                break;
            case R.id.withdrawUI_tvBindAlipay:
                intent = new Intent(context, BindAlipayActivity.class);
                intent.putExtra(IntentParamUtils.USERNAME, userName);
                intent.putExtra(IntentParamUtils.REALNAME, realName);
                startActivity(intent);
                break;
            case R.id.ll_bankinfo:
                if (isManage) {
                    deleteType = 0;
                    showSureDialog();
                } else {
                    chooseInfo = bankInfo;
//                    alipayInfo_rb.setChecked(false);
                    bankInfo_rb.setChecked(true);
                }
                break;
//            case R.id.ll_alipayinfo:
//                if (isManage) {
//                    deleteType = 1;
//                    showSureDialog();
//                } else {
//                    chooseInfo = alipayInfo;
//                    bankInfo_rb.setChecked(false);
//                    alipayInfo_rb.setChecked(true);
//                }
//                break;
            case R.id.withdrawUI_tvOk:

                if (et_yanZheng()) {
                    requestTixian();
                }

                break;
            default:
                break;
        }
    }

    @Override
    public void onRightClick() {
        Intent intent = new Intent(context, WithDrawRecordActivity.class);
        startActivity(intent);
    }

    SureDialog sureDialog;

    /**
     * 确认支付对话框
     */
    public void showSureDialog() {

        SureDialog.OnDialogOKCancleClickListener listener = new SureDialog.OnDialogOKCancleClickListener() {

            @Override
            public void onOKClick() {

                if (deleteType == 0) {
                    requestUnBind(bankInfo.getId());
                } else {
//                    requestUnBind(alipayInfo.getId());
                }
                sureDialog.dismiss();
            }

            @Override
            public void onCancleClick() {
                sureDialog.dismiss();
            }
        };

        sureDialog = new SureDialog(this, listener, "", "确定要删除吗？", "确定", "取消");

        sureDialog.show();
    }

}
